enum IResource {
	VIDEO = 'video',
	Page = 'page'
}

interface IResourceProps {
	type: IResource;
	url: string;
	name: string;
}

import { urlToBase64 } from '@/modules/utils';
import { BusinessTaskMap, IBusinessStatus, IBusinessName } from '../BusinessContext';
import { uploadFileWithBlob, compareFace, contrastverify } from '@/api';
import { dataURItoBlob, getCustomerUserId } from '@/utils';
import { saveFaceRecognition, stopScreenShare, saveCardRecognition } from '@/utils/lib';
import Message from '@/utils/message';
import MessageEnum from '@/utils/MessageEnum';
import AgentService from '@/modules/Agent';
import store from '@/store';
import i18next from '../../../utils/i18next/i18n';
import {
	cancelCardCollectionErrorResponse,
	cancelCollectShortVideoErrorResponse,
	cancelCollectVariableErrorResponse,
	cancelHandWritingErrorResponse,
	cancelPdfWhiteboardErrorResponse,
	cancelRequestFillFormErrorResponse,
	cancelRequestLocationErrorResponse,
	cancelScannerCodeErrorResponse,
	cancelTestimonyWriteErrorResponse,
	cancelWhiteboardErrorResponse,
	cardCollectionErrorResponse,
	collectShortVideoErrorResponse,
	deleteWhiteboardErrorResponse,
	requestFillFormErrorResponse,
	requestGeolocationErrorResponse,
	requestHandSignErrorResponse,
	screenCaptureErrorResponse,
	screenshotErrorResponse,
	sendCollectVariableErrorResponse,
	sendLinkErrorResponse,
	sendPDFErrorResponse,
	sendPdfWhiteboardErrorResponse,
	sendScannerCodeErrorResponse,
	sendTestimonyWriteErrorResponse,
	sendVideoLinkErrorResponse,
	sendWhiteBoardErrorResponse,
	startWhiteboardErrorResponse,
	cancelCustomerViewMarkErrorResponse,
	sendCustomerViewMarkCodeErrorResponse
} from '@/modules/errorResponse';
const { t } = i18next;

//截屏
const screenshot = (clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.screenshot(
			undefined,
			clientId,
			async (resp: any) => {
				const data = await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(data);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(clientId);
				screenshotErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//屏幕共享
const screenShare = () => {
	return new Promise((resolve, reject) => {
		ivcs.agent.screenShare(
			async (success: any) => {
				resolve(success);
			},
			async (onFailure: any) => {
				Message.warning(t('operation-failed'));
				reject(onFailure);
			},
			async (onStop: any) => {
				reject(onStop);
			},
			`${AgentService.user?.userName}-screen`,
			''
		);
	});
};

// 扫码
const sendScannerCode = (clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.requestCustomerScanCode(
			undefined,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendScannerCodeErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 取消扫码
const cancelScannerCode = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelCustomerScanCode(
			cmdId,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelScannerCodeErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

/**
 * 发送实时标注指令
 * @param clientId 发送的访客clientId
 * @param videoId  发送的访客流的videoId，用来渲染画面的
 * @returns
 */
const customerViewMark = (clientId: string, videoId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.customerViewMark(
			{ videoId },
			clientId,
			async (success: any) => {
				console.log('customerViewMark success', success);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				console.log('customerViewMark error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendCustomerViewMarkCodeErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 取消实时标注
const cancelCustomerViewMark = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelCustomerViewMark(
			cmdId,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelCustomerViewMarkErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 请求获取地理位置
const requestGeolocation = (clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.requestCustomerLocation(
			undefined,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				requestGeolocationErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消获取地理位置
const cancelRequestCustomerLocation = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelRequestCustomerLocation(
			cmdId,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelRequestLocationErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 资源分享
const sendViewResource = (data: IResourceProps, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendViewResource(
			data,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				reject(error);
			}
		);
	});
};

//推送链接
const sendLink = (link: string, clientId: string) => {
	let data = {
		url: link,
		name: link,
		type: 'page'
	};
	return new Promise((resolve, reject) => {
		ivcs.agent.sendViewResource(
			data,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendLinkErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 推送视频
const sendVideoLink = (videoLink: string, clientId: string) => {
	let data = {
		url: videoLink,
		name: videoLink,
		type: 'video'
	};
	return new Promise((resolve, reject) => {
		ivcs.agent.sendViewResource(
			data,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendVideoLinkErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 推送Pdf
const sendPDF = (resource: { name: string; url: string; size: number }, clientId: string) => {
	let data = {
		...resource,
		type: 'paper'
	};
	return new Promise((resolve, reject) => {
		ivcs.agent.sendViewResource(
			data,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendPDFErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 发送自定义消息
const sendCustomizeMessage = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendCustomMessage(
			data,
			clientId,
			(success: any) => resolve(success),
			(error: any) => reject(error)
		);
	});
};

//截屏
const screenCapture = (clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.screenCapture(
			undefined,
			clientId,
			async (resp: any) => {
				const data = await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(data);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(clientId);
				screenCaptureErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//录屏
const startRecordScreen = (clientId: string, systemStop: () => void) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.startRecordScreen(
			async (resp: any) => {
				const data = await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				console.log('startRecordScreen:', data, resp);
				resolve({ data, ...resp });
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(clientId);
				Message.warning(t('operation-failed'));
				reject(error);
			},
			async (stop: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.DONE, null);
				await BusinessTaskMap.delTask(clientId);
				// Message.normal('录制已停止');
				systemStop();
				reject(stop);
			},
			async (recordError: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(clientId);
				Message.warning(t('screen-recording-file-storage-failed'));
				reject(recordError);
			}
		);
	});
};

const stopRecordScreen = (clientId: string, publicationId: string, recordId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.stopRecordScreen(
			publicationId,
			recordId,
			async (scuuess: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.DONE, null);
				await BusinessTaskMap.delTask(clientId);
				// Message.normal('录制已停止');
				resolve(scuuess);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				Message.warning(t('STOP_RECORD_FAILED'));
				reject(error);
			}
		);
	});
};

// 人脸比对
const faceRecognition = async (id: string, clientId: string) => {
	let canvas: HTMLCanvasElement = document.getElementById(`${id}canvas`) as HTMLCanvasElement;
	let context = canvas && canvas.getContext('2d');
	let video: any = document.getElementById(id);
	console.log(canvas, context, video);
	context && context.drawImage(video, 0, 0, window.screen.width * 0.24, 350);
	let imageDataUrl = canvas.toDataURL('image/png');
	console.log('base64', imageDataUrl);

	return new Promise((resolve, reject) => {
		try {
			let fileName = Date.now() + '.png';
			let blob = dataURItoBlob(imageDataUrl);
			uploadFileWithBlob(blob, fileName)
				.then(async resp => {
					console.log('upload file', resp);
					let userId = getCustomerUserId(clientId, store.getState().session.members.length !== 0 ? store.getState().session.members : AgentService.sessionMembers);
					let url = AgentService.configure.awsFileUrl ? AgentService.configure.awsFileUrl + resp.data.data.url : resp.data.data.url;
					const result = await compareFaceFunction(userId, url, clientId);
					resolve(result);
				})
				.catch(error => {
					console.log(error, 'uploadFileWithBlob error');
					BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
					reject(error);
				});
		} catch (e) {
			console.log();
			reject(e);
		}
	});
};

const compareFaceFunction = async (userId: string, imageUrl: string, clientId: string) => {
	const role = AgentService.getCustomerMediaStream().find(item => item.clientId === clientId)?.customerRole;
	const customerVariables = AgentService.customerVariableList.filter(item => item.roleName === role);
	let para = {
		imageUrl: imageUrl,
		imageUrl1: customerVariables.find(item => item.linkedKey === 'picture')?.value ? customerVariables.find(item => item.linkedKey === 'picture')?.value : '',
		ImageDataA: '',
		ImageDataB: ''
	};
	let data = {
		imageUrl: imageUrl,
		result: ''
	};
	try {
		// 人脸比对接口，参数支持 base64 图片
		try {
			await urlToBase64(para.imageUrl).then((s: any) => {
				para.ImageDataA = s;
			});
			await urlToBase64(para.imageUrl1).then((s: any) => {
				para.ImageDataB = s;
			});
		} catch (error) {
			console.log('urltoBase64 error', error);
		}
		const resp = await compareFace(userId, para);
		if (resp.data === 1) {
			data.result = 'yes';
			console.log('本人');
			saveFaceRecognition(data, clientId);
		} else if (resp.data === 0) {
			data.result = 'no';
			console.log('不是本人');
			saveFaceRecognition(data, clientId);
		} else if (resp.data === -1) {
			data.result = 'noface';
			console.log('没有人脸');
			saveFaceRecognition(data, clientId);
		}
		await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.DONE, null);
		const task = await BusinessTaskMap.getTask(clientId);
		if (task) {
			const message = resp.data === 1 ? MessageEnum.FACE_COMPARE_PASS : MessageEnum.FACE_COMPARE_FAILED;
			const client = t('client');
			Message.notify(`${client}<${task.username}>${message}`);
			await BusinessTaskMap.addCompletedTask({ task: IBusinessName.FACE_COMPARE, data: task, response: data, isRead: false });
		}
	} catch (error) {
		console.log(error);
		data.result = 'apiError';
		saveFaceRecognition(data, clientId);
		await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
		const task = await BusinessTaskMap.getTask(clientId);
		if (task) {
			const message = MessageEnum.FACE_COMPARE_FAILED;
			const client = t('client');
			Message.notify(`${client}<${task.username}>${message}`);
			await BusinessTaskMap.addCompletedTask({ task: IBusinessName.FACE_COMPARE, data: task, response: data, isRead: false });
			console.log('BusinessTaskMap:', BusinessTaskMap.getComletedTask());
		}
	}
	return data;
};

const cardRecognition = async (id: string, clientId: string) => {
	let canvas: HTMLCanvasElement = document.getElementById(`${id}canvas`) as HTMLCanvasElement;
	let context = canvas && canvas.getContext('2d');
	let video: any = document.getElementById(id);
	console.log(canvas, context, video);
	context && context.drawImage(video, 0, 0, window.screen.width * 0.24, 350);
	let imageDataUrl = canvas.toDataURL('image/png');
	// console.log('base64', imageDataUrl);
	return new Promise((resolve, reject) => {
		let fileName = Date.now() + '.png';
		let blob = dataURItoBlob(imageDataUrl);
		uploadFileWithBlob(blob, fileName)
			.then(async resp => {
				console.log('upload file', resp);
				let url = AgentService.configure.awsFileUrl ? AgentService.configure.awsFileUrl + resp.data.data.url : resp.data.data.url;
				const compareRes: any = await cardCompare(imageDataUrl, url, clientId);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.DONE, null);
				const task = await BusinessTaskMap.getTask(clientId);
				if (task) {
					const message = compareRes.result === 'success' ? MessageEnum.CARD_COMPARE_PASS : MessageEnum.CARD_COMPARE_FAILED;
					const client = t('client');
					Message.notify(`${client}<${task.username}>${message}`);
					await BusinessTaskMap.addCompletedTask({ task: IBusinessName.FACE_COMPARE, data: task, response: compareRes, isRead: false });
				}
				resolve(compareRes);
			})
			.catch(async error => {
				console.log(error, 'uploadFileWithBlob error');
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				const task = await BusinessTaskMap.getTask(clientId);
				if (task) {
					await BusinessTaskMap.addCompletedTask({ task: IBusinessName.FACE_COMPARE, data: task, response: error, isRead: false });
				}
				reject(error);
			});
	});
};

// 人证对比
const cardCompare = async (imageBase64: string, imageDataUrl: string, clientId: string) => {
	const role = AgentService.getCustomerMediaStream().find(item => item.clientId === clientId)?.customerRole;
	const customerVariables = AgentService.customerVariableList.filter(item => item.roleName === role);
	console.log('customerVariables', customerVariables, role, AgentService.customerVariableList);
	let para = {
		certName: customerVariables.find(item => item.linkedKey === 'fullName')?.value,
		certNo: customerVariables.find(item => item.linkedKey === 'idCardNo')?.value,
		faceContrastPicture: imageBase64.replace('data:image/png;base64,', '')
	};
	let data = {
		imageUrl: imageDataUrl,
		result: '',
		data: {
			reason: ''
		}
	};

	return new Promise(async (resolve, reject) => {
		try {
			if (!para.certName || !para.certNo) {
				data.result = !para.certName ? 'invalid-name' : 'invalid-name';
				data.data.reason = !para.certName ? 'invalid-name' : 'invalid-name';
				saveCardRecognition(data, clientId);
			} else {
				// console.log('para', para);
				let resp = await contrastverify(para);
				data.result = resp.data?.result;
				data.data = resp.data;
				console.log(resp, 'cardCompare result');
				saveCardRecognition(data, clientId);
			}
		} catch (error) {
			data.result = 'failed';
			console.log(error, 'cardCompare error');
			saveCardRecognition(data, clientId);
		}
		resolve(data);
	});
};

// 停止屏幕共享
const endScreenShare = async (screenShareId: string, saveRecord = true) => {
	console.log('screenShareId:', screenShareId);
	try {
		const resp = await stopScreenShare(screenShareId);
		console.log('stop screen share success', resp);
		const container = document.getElementById('widget-screen-share-parent-contianer');
		container && document.body.removeChild(container);
	} catch (error) {
		console.log('stop screen share error', error);
		const container = document.getElementById('widget-screen-share-parent-contianer');
		container && document.body.removeChild(container);
	}

	// if (saveRecord) {
	// 	const tasks = BusinessTaskMap.findTaskWithTaskName(IBusinessName.SCREEN_SHARE);
	// 	console.log(tasks, BusinessTaskMap);

	// 	tasks.map(item => {
	// 		saveStopScreenShareRecord(item.clientId);
	// 	});
	// }
};

// 推送签名
const requestHandSign = (clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.inviteHandWriting(
			undefined,
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				console.log(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				console.log(error);
				requestHandSignErrorResponse(error.code || '');
			}
		);
	});
};

//取消签名
const cancelHandWriting = async (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelHandWriting(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelHandWriting success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelHandWriting error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelHandWritingErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//推送表单
const requestFillForm = async (clientId: string, formData: any) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendOnlineForm(
			formData,
			clientId,
			async (resp: any) => {
				const data = await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve({ data, formData, cmdId: resp.cmdId });
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				requestFillFormErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消表单填写
const cancelRequestFillForm = async (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelOnlineForm(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelOnlineForm success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelOnlineForm error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelRequestFillFormErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 保存对某一个访客开启屏幕共享，用于业务系统留痕
const saveScreenShareRecord = async (clientId: string) => {
	ivcs.agent.saveScreenShareRecord(clientId);
};

// 保存对某一个访客停止屏幕共享，用于业务系统留痕
const saveStopScreenShareRecord = async (clientId: string) => {
	ivcs.agent.saveStopScreenShareRecord(clientId);
};

// 采集身份证正反面
const requestCollectIdCard = (clientId: string, autoOcr: boolean) => {
	console.log('requestCollectIdCard', clientId, autoOcr);

	return new Promise((resolve, reject) => {
		ivcs.agent.collectIdCard(
			{ autoOcr: autoOcr }, //默认为{},表明采集正反面
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				cardCollectionErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};
// 取消身份证采集
const cancelIdCardCollection = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelIdCardCollection(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelIdCardCollection success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelIdCardCollection error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelCardCollectionErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};
// 采集银行卡
const requestCollectBankCard = (clientId: string, autoOcr: boolean) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.collectBankCard(
			{ autoOcr: autoOcr }, //默认为{},表明采集正反面
			clientId,
			async (success: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				resolve(success);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				cardCollectionErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};
// 取消银行卡采集
const cancelBankCardCollection = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelBankCardCollection(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelBankCardCollection success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelBankCardCollection error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				cancelCardCollectionErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//开启白板
const startWhiteboard = (name: string, path: string, hostname: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.startWhiteboard(
			name,
			path,
			hostname,
			(resp: any) => {
				console.log('startWhiteboard success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('startWhiteboard error', error);
				startWhiteboardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//删除白板
const deleteWhiteboard = (whiteboardId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.deleteWhiteboard(
			whiteboardId,
			(resp: any) => {
				console.log('deleteWhiteboard success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('deleteWhiteboard error', error);
				deleteWhiteboardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//发送共享白板指令
const sendWhiteBoard = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendWhiteboard(
			data,
			clientId,
			async (resp: any) => {
				console.log('send white board success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('send white board error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				sendWhiteBoardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消共享白板指令
const cancelWhiteBoard = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelWhiteboard(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelWhiteBoard success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelWhiteBoard error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				cancelWhiteboardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//开启pdf白板
const startPdfWhiteboard = (name: string, path: string, hostname: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.startPdfWhiteboard(
			name,
			path,
			hostname,
			(resp: any) => {
				console.log('startPdfWhiteboard success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('startPdfWhiteboard error', error);
				reject(error);
			}
		);
	});
};

//删除pdf白板
const deletePdfWhiteboard = (whiteboardId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.deletePdfWhiteboard(
			whiteboardId,
			(resp: any) => {
				console.log('deletePdfWhiteboard success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('deletePdfWhiteboard error', error);
				reject(error);
			}
		);
	});
};

//发送共享PDF指令
const sendPdfWhiteboard = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendPdfWhiteboard(
			data,
			clientId,
			async (resp: any) => {
				console.log('sendPdfWhiteboard success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('sendPdfWhiteboard error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				sendPdfWhiteboardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消共享PDF指令
const cancelPdfWhiteboard = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelPdfWhiteboard(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelPdfWhiteboard success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelPdfWhiteboard error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				cancelPdfWhiteboardErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//开启证言抄录白板
const startTestimonyWrite = (name: string, path: string, hostname: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.startTestimonyWrite(
			name,
			path,
			hostname,
			(resp: any) => {
				console.log('startTestimonyWrite success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('startTestimonyWrite error', error);
				reject(error);
			}
		);
	});
};

//删除证言抄录白板
const deleteTestimonyWrite = (whiteboardId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.deleteTestimonyWrite(
			whiteboardId,
			(resp: any) => {
				console.log('deleteTestimonyWrite success', resp);
				resolve(resp);
			},
			(error: any) => {
				console.log('deleteTestimonyWrite error', error);
				reject(error);
			}
		);
	});
};

//发送证言抄录
const sendTestimonyWrite = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.sendTestimonyWrite(
			data,
			clientId,
			async (resp: any) => {
				console.log('sendTestimonyWrite success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('sendTestimonyWrite error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				sendTestimonyWriteErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消证言抄录
const cancelTestimonyWrite = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelTestimonyWrite(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelTestimonyWrite success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelTestimonyWrite error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				cancelTestimonyWriteErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//发送变量收集
const sendCollectVariable = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.collectVariable(
			data,
			clientId,
			async (resp: any) => {
				console.log('collectVariable success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('collectVariable error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendCollectVariableErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消变量采集
const cancelCollectVariable = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelCollectVariable(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelCollectVariable success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelCollectVariable error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				cancelCollectVariableErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//发起短视频采集
const collectShortVideo = (data: any, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.collectShortVideo(
			data,
			clientId,
			async (resp: any) => {
				console.log('collectShortVideo success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, resp.cmdId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('collectShortVideo error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				collectShortVideoErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

//取消短视频采集
const cancelCollectShortVideo = (cmdId: string, clientId: string) => {
	return new Promise((resolve, reject) => {
		ivcs.agent.cancelCollectShortVideo(
			cmdId,
			clientId,
			async (resp: any) => {
				console.log('cancelCollectShortVideo success', resp);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.CANCEL, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				resolve(resp);
			},
			async (error: any) => {
				console.log('cancelCollectShortVideo error', error);
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, Number(cmdId));
				await BusinessTaskMap.delTask(clientId);
				cancelCollectShortVideoErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

// 开启屏幕区域录屏，借助(chrome)屏幕共享功能,录制特定区域
const startRecordRegionalScreen = (clientId: string, dom: any, systemStop: () => void) => {
	let key = clientId + `-${IBusinessName.REGIONAL_SCREEN_RECORDING}`;
	return new Promise((resolve, reject) => {
		ivcs.agent.startRecordRegionalScreen(
			dom,
			async (resp: any) => {
				const data = await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.IN_PROGRESS, resp.recordId);
				console.log('startRecordRegionalScreen:', data, resp);
				Message.normal(t('initiate-regional-screen-recording'));
				resolve({ data, ...resp });
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(key);
				// 60028:不支持非标签页的区域录屏 60024 报错。操作失败！
				if (error.code === '60028') {
					Message.warning(t('regional-screen-recording-error-60028'));
				} else if (error.code === '60024') {
					Message.warning(t('operation-failed'));
				}
				reject(error);
			},
			async (stop: any) => {
				await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.DONE, null);
				await BusinessTaskMap.delTask(key);
				// Message.normal('录制已停止');
				systemStop();
				reject(stop);
			},
			async (recordError: any) => {
				await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.IDLE, null);
				await BusinessTaskMap.delTask(key);
				Message.warning(t('regional-screen-recording-file-storage-failed'));
				reject(recordError);
			}
		);
	});
};

// 停止区域屏幕录制
const stopRecordRegionalScreen = (clientId: string, publicationId: string, recordId: string) => {
	let key = clientId + `-${IBusinessName.REGIONAL_SCREEN_RECORDING}`;
	return new Promise((resolve, reject) => {
		ivcs.agent.stopRecordRegionalScreen(
			publicationId,
			recordId,
			async (scuuess: any) => {
				await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.DONE, null);
				await BusinessTaskMap.delTask(key);
				// Message.normal('录制已停止');
				resolve(scuuess);
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.FAILED, null);
				Message.warning(t('STOP_REGION_RECORD_FAILED'));
				reject(error);
			}
		);
	});
};

// 推送知识库链接
const sendKnowledgeBase = (resource: { catagory: string; questionId: string }, clientId: string) => {
	let data = {
		...resource,
		type: 'knowledgeBase'
	};
	return new Promise((resolve, reject) => {
		ivcs.agent.sendViewResource(
			data,
			clientId,
			async (success: any) => {
				try {
					await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.IN_PROGRESS, success.cmdId);
				} catch (error) {
				} finally {
					resolve(success);
				}
			},
			async (error: any) => {
				await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.FAILED, null);
				await BusinessTaskMap.delTask(clientId);
				sendPDFErrorResponse(error.code || '');
				reject(error);
			}
		);
	});
};

export {
	screenshot,
	screenShare,
	sendPDF,
	sendVideoLink,
	sendCustomizeMessage,
	sendViewResource,
	sendScannerCode,
	requestHandSign,
	cancelScannerCode,
	requestGeolocation,
	sendLink,
	screenCapture,
	startRecordScreen,
	cardRecognition,
	faceRecognition,
	endScreenShare,
	stopRecordScreen,
	cancelRequestCustomerLocation,
	cancelHandWriting,
	requestFillForm,
	cancelRequestFillForm,
	saveScreenShareRecord,
	saveStopScreenShareRecord,
	requestCollectIdCard,
	cancelIdCardCollection,
	requestCollectBankCard,
	cancelBankCardCollection,
	sendWhiteBoard,
	cancelWhiteBoard,
	sendPdfWhiteboard,
	cancelPdfWhiteboard,
	sendTestimonyWrite,
	cancelTestimonyWrite,
	sendCollectVariable,
	cancelCollectVariable,
	startWhiteboard,
	deleteWhiteboard,
	startPdfWhiteboard,
	deletePdfWhiteboard,
	startTestimonyWrite,
	deleteTestimonyWrite,
	collectShortVideo,
	cancelCollectShortVideo,
	startRecordRegionalScreen,
	stopRecordRegionalScreen,
	sendKnowledgeBase,
	customerViewMark,
	cancelCustomerViewMark
};
